package cool.gaogao.transactional.config;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author 高山青
 * @Date 2021/12/31  -   15:56
 */
@Configuration
@ComponentScan(basePackages = "cool.gaogao.transactional")
@EnableTransactionManagement//开启事务
public class AccountConfig {




	@Bean
	public JdbcTemplate getJdbcTemplate(DataSource dataSource){
		JdbcTemplate jdbcTemplate=new JdbcTemplate();
		jdbcTemplate.setDataSource(dataSource);
		return jdbcTemplate;
	}


	@Bean
	public DataSource dataSource() throws Exception {
		//1.从类路径下加载配置文件，获取一个输入流。如果不指定路径，默认是读取同一个包下资源文件
		InputStream inputStream = AccountConfig.class.getResourceAsStream("/jdbc.properties");
		//2.使用Properties对象的方法将配置文件中属性加载到Properties对象中
		Properties properties = new Properties();
		//加载了配置文件中所有的属性
		properties.load(inputStream);
		//3.通过druid的工厂类创建连接池
		DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);

		//获取10个连接对象
	/*	for (int i = 1; i <= 11; i++) {
			Connection connection = dataSource.getConnection();
			System.out.println("第" + i + "个连接对象：" + connection);
			//第3个连接关闭
			if (i == 3) {
				connection.close();
			}
		}*/


		return dataSource;
	}

	//配置事务管理
	@Bean
	public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
		DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
		dataSourceTransactionManager.setDataSource(dataSource);
		return dataSourceTransactionManager;
	}


}
